#!/usr/bin/python

import re, model, cgi, sqlobject
from model import Node
from sqlobject import SQLObjectNotFound
from cgi import escape

bold = re.compile(r'\*(\S.*?\S)\*')
italic = re.compile(r'/(\S.*?\S)/')
link = re.compile(r'\[(\S.*?\S)\]')

def markup(str):
    """ Markup system used in uberwiki
        *bold* /italics/ [link]
    """

    def linkify(match):
        name = match.group(1)
        title=''
        try:
            node = Node.byName(name)
            if node.definition:
                class_ = 'defined'
                title = 'title="%s"'
                title %= escape(node.definition, quote=True)
            else:
                class_ = 'found'
        except SQLObjectNotFound:
            class_ = 'notfound'

        str = '<a href="%s" class="%s" %s>%s</a>'
        str %= (name, class_, title, name)

        return str

    str = escape(str)
    str = italic.sub(r'<i>\1</i>', str)
    str = bold.sub(r'<b>\1</b>', str)
    str = link.sub(linkify, str)
    return str


def get_referances(str):
    """ Returns the set of linked names """

    s = set()
    for match in link.finditer(str):
        s.add(match.group(1))

    return s

